<template>
  <v-layout type="main">
    <p class="page-title">强化学习开发</p>
    <div class="detail-box" v-if="!$route.meta.hideDetails && detailData">
      <div class="pic">
        <v-image class="avatar" :src="detailData.avatar" alt="" />
      </div>
      <div class="word">
        <h3 class="title">
          <!-- {{detailData.alias}} -->
          {{ detailData.name }} <i class="el-icon-edit-outline alick-btn-edit" @click="updateBase" /> <!-- <span>状态：<strong
              :class="['alick-layout-status', detailData.status]">{{ statusMap[detailData.status]}}</strong></span>-->
          <el-button class="back" type="text" icon="el-icon-right" @click="$router.push({ path: '/gameExperiment' })" />
        </h3>
        <p class="hint">{{ detailData.desc }}</p>
        <div class="alick-handle-btns">
          <a class="handle-btn" href="javascript:;" @click="start" v-show="detailData.status == 'terminated'">启动</a>
          <a class="handle-btn" href="javascript:;" @click="goToTensorboard"
            v-show="detailData.status == 'running' && detailData.tensorboard == true">tensorboard</a>
          <a class="handle-btn" href="javascript:;" @click="goToLink" v-show="detailData.status == 'running'">打开仿真前端</a>
          <!-- <a class="handle-btn" href="javascript:;" @click="entry" v-show="detailData.status == 'running'">进入VSCode</a> -->
          <el-popover placement="bottom-end" width="80" trigger="hover" v-show="detailData.status == 'running'">
            <div class="alick-popover-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="entry">进入VSCode</a>
              <a class="handle-btn" href="javascript:;" @click="entryBt">强化学习行为树</a>
            </div>
            <a class="handle-btn" href="javascript:;" slot="reference">模型开发</a>
          </el-popover>
          <a class="handle-btn" href="javascript:;" @click="stop" v-show="detailData.status != 'terminated'">停止</a>
          <el-popover placement="bottom-end" width="80" trigger="hover">
            <div class="alick-popover-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="exportModel">导出模型</a>
              <a class="handle-btn" href="javascript:;" @click="exportTask">训练任务</a>
              <a class="handle-btn" href="javascript:;" @click="exportAlgorithm">发布到公开算法</a>
            </div>
            <a class="handle-btn" href="javascript:;" slot="reference">更多</a>
          </el-popover>
        </div>
      </div>
    </div>
    <el-radio-group v-model="nowRouter" size="medium" @change="skip" class="nav-alike" v-show="!$route.meta.hideDetails">
      <el-radio-button :label="e.name" v-for="(e, i) in thisRouter" :key="i">
        <span class="nav-alike-item">{{ e.meta.title }}</span>
      </el-radio-button>
    </el-radio-group>
    <div :class="['layout-content', { 'layout-content-nodetail': $route.meta.hideDetails }]">

      <router-view class="content-detail" :detailData.sync="detailData" @infoData="infoData" v-if="detailData" />
    </div>

    <div v-if="showExportModelDialog">
      <plug-export-model :show_file.sync=showExportModelDialog @infoShow="infoShowExport" :model_id=model_id
        :biz_id=detailData.id :business_type="3" />
    </div>

    <el-dialog :visible.sync="showUpdateBaseDialog" title="模型开发基本信息" width="840px">
      <el-form class="form myself-form" ref="form" :rules="baseSubmitRules" :model="taskForm" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="taskForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="taskForm.desc" />
        </el-form-item>
        <el-form-item label="配图">
          <media-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" :src="taskForm.avatar" @avatarPath="avatarPath" />
        </el-form-item>
        <el-form-item label="" prop="tensorboard">
          <el-checkbox v-model="taskForm.tensorboard">tensorboard</el-checkbox>
        </el-form-item>
        <el-form-item label=" ">
          <el-button class="none-type" type="primary" @click="commitBase">确定</el-button>
          <el-button class="none-type" @click="cancelBase">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </v-layout>
</template>

<script>
import { getMarketAlgorithmBySource } from "@/api/marketAlgorithm"
import { getGameTaskBySource } from "@/api/gameTask"
import { getGameExperimentDetail, putGameExperiment, startGameExperiment, stopGameExperiment } from '@/api/gameExperiment'
import { domain } from '@/config'
import { getModelBySource } from "@/api/model"
import plugExportModel from '@/components/module/plug-export-model'
export default {
  data() {
    return {
      nowRouter: this.$route.name,
      thisRouter: [],
      detailData: null,
      taskForm: {},
      model_id: null,
      modelForm: { visibility: 0 },
      marketForm: {},
      taskSubmitRules: {
        task_id: [
          { required: true, message: "该项为必填项" },
        ]
      },
      baseSubmitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到40个字符" },
        ],
      },
      modelSubmitRules: {
        model_id: [
          { required: true, message: "该项为必填项" },
        ]
      },
      marketSubmitRules: {
        model_id: [
          { required: true, message: "该项为必填项" },
        ]
      },
      showTaskDialog: false,
      showMarketDialog: false,
      showUpdateBaseDialog: false,
      showExportModelDialog: false,
      taskOptions: [],
      modelOptions: [],
      marketAlgorithmOptions: [],
      task: null,
      model: null,
      algorithm: null,
      podUrl: null,
      simulationHomeUrl: null
    };
  },
  components: {
    plugExportModel
  },
  methods: {
    skip() {
      let path = `/gameExperiment/${this.thisRouter.filter(e => e.name == this.nowRouter)[0].path}`
      if (path == this.$route.path) return
      this.$router.push({
        path,
        query: {
          id: this.$route.query.id
        }
      })
    },

    async getDetail() {
      if (!this.$route.query.id) return
      let res = await getGameExperimentDetail({ id: this.$route.query.id });
      if (res && res.data) {
        this.detailData = res.data;
        this.taskForm = JSON.parse(JSON.stringify(this.detailData))
        if (this.taskForm.simulation_home_url) {
          this.simulationHomeUrl = this.taskForm.simulation_home_url
        }
      }
      this.genUrl()
    },
    avatarPath(data) {
      this.taskForm.avatar = data;
    },
    updateBase() {
      this.showUpdateBaseDialog = true
    },

    commitBase() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res = await putGameExperiment(this.taskForm);
          if (res && res.data) {
            this.getDetail()
            this.showUpdateBaseDialog = false
          }
        }
      })
    },
    cancelBase() {
      this.showUpdateBaseDialog = false
    },
    async exportTask() {
      if (!this.$route.query.id) return
      let data = {
        source: this.detailData.id
      }
      let task_id = null
      let res = await getGameTaskBySource(data);
      if (res && res.data) {
        task_id = res.data.id
      }
      let query = {
        experiment_id: this.detailData.id,
        task_id: task_id
      }
      this.$router.push({
        path: '/gameTask/detail',
        query
      })
    },
    async exportModel() {
      if (!this.$route.query.id) return
      let data = {
        source: this.detailData.id
      }
      let res = await getModelBySource(data);
      if (res && res.data) {
        this.model_id = res.data.id
      }
      this.showExportModelDialog = true
    },

    infoShowExport(data) {
      this.showExportModelDialog = data
    },

    infoData(data) {
      console.log("infoData", data)
      this.getDetail()
      this.$forceUpdate()
    },
    async exportAlgorithm() {
      if (!this.$route.query.id) return
      let data = {
        source: this.detailData.id
      }
      let res = await getMarketAlgorithmBySource(data);
      let algorithm_id = null
      console.log("res", res)
      if (res && res.data) {
        algorithm_id = res.data.id
      }
      console.log("res2", res)
      let query = {
        experiment_id: this.detailData.id,
        algorithm_id: algorithm_id
      }
      console.log("query", query)
      this.$router.push({
        path: '/algorithm/detail',
        query
      })
    },
    update() {
      let query = {
        id: this.detailData.id
      }
      this.$router.push({
        path: '/gameExperiment/detail',
        query
      })
    },

    start() {
      startGameExperiment({ id: this.detailData.id });

    },
    async stop() {
      await stopGameExperiment({ id: this.detailData.id });
      this.getDetail()
      this.$forceUpdate()

    },
    entry() {
      let path = `${domain.split(':')[1]}:32658` + this.detailData.pod_url
      // let path = "http://192.168.240.11:32658" + this.detailData.pod_url // 中船
      console.log('path', path)
      window.open(path, '_blank');
    },
    entryBt() {
      const { href } = this.$router.resolve({
        path: '/bTree',//路径
        query: {
          experiment_id: this.detailData.id,
        }//传参
      });
      window.open(href)

    },
    goToLink() {
      // 增加自动化所仿真地址规则
      if (this.simulationHomeUrl) {
        window.open(this.simulationHomeUrl, '_blank');
        return;
      }
      let path = this.podUrl;
      if (this.podUrl == null) {
        alert('仿真前端地址解析失败, 请在刷新页面后重试')
        return;
      }
      window.open(path, '_blank');
    },
    goToTensorboard() {
      let path = `${domain.split(':')[1]}:8081` + this.detailData.tensorboard_url
      console.log('path', path)
      window.open(path, '_blank');
    },
    genUrl() {
      if (this.detailData.status != 'running' || !this.detailData.tcp_port_list) {
        return null;
      }
      try {
        let tcp_port_list = this.detailData.tcp_port_list
        let simulationFrontUrl = process.env.VUE_APP_SIMULATION_URL;
        let port4000List = tcp_port_list.filter(map => map.containerPort == '4000')
        let nodePort4000 = port4000List[0].nodePort;
        let frontPort = 4001;
        let port4001List = tcp_port_list.filter(map => map.containerPort == '4001')
        let frontMap = port4001List[0].nodePort;
        let nodePort4009 = null;
        if (tcp_port_list.length > 9) {
          let port4009List = tcp_port_list.filter(map => map.containerPort == '4009')
          if (port4009List.length) {
            nodePort4009 = port4009List[0].nodePort;
          }
        }
        let endpoint = tcp_port_list[0].endpoint.split(':')[0];
        if (nodePort4009 != null) {
          frontPort = 4009;
          frontMap = nodePort4009;
        }
        let url = `${simulationFrontUrl}/#/Menu?IP=${endpoint}&port1=${nodePort4000}&port2=${frontPort}&port3=${frontMap}`;
        this.podUrl = url;
      }
      catch (error) {
        console.error(error)
      }
    }
  },
  mounted() {
    let temp = this.$router.options.routes.filter(
      e => e.name == 'gameExperiment' && e.children
    )
    this.thisRouter = temp[0].children.filter(e => !e.meta.hideDetails)
    this.getDetail()
    this.$EventBus.$on('experiment', e => {
      console.log(e)
      this.getDetail()
    })
  },
  destroyed() {
    this.$EventBus.$off('experiment')
  },
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";
</style>
